import { defineStore } from "pinia";
import { ref, reactive, watch } from "vue";
import {
  tenantUpdateToken,
  tenantList,
  messageList,
  messageQuantity,
} from "@/api/user";
import { useTokenStore } from "../token";

const useUserStore = defineStore(
  // 唯一ID
  "user",
  () => {
    const isLogin = reactive({
      value: uni.getStorageSync("token").value ? 1 : 0,
      popShow: false,
    });
    const initialUserInfo = {
      nickName: "Hi, 欢迎进入~",
      phoneNum: "",
      memberId: "",
      customerId: "",
      avatarUrl: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/default-avatar.png",
      residence: "",
    };

    const initialTenant = {
      value: "", // 租户id 登录时保存
      currentTenant: "",
      option: [],
    };
    // 初始化 reactive 对象
    const userInfo = reactive({ ...initialUserInfo });
    const tenant = reactive({ ...initialTenant });
    // 创建重置函数
    function resetUserInfoAndTenant() {
      Object.assign(userInfo, initialUserInfo);
      Object.assign(tenant, initialTenant);
    }
    // 获取租户列表， 【我的】页面顶部切换
    const updateToken = async () => {
      const result = await tenantUpdateToken({
        tenantId: uni.getStorageSync("tenantId") || tenant.value,
      });
      return result;
    };
    const getTenantList = async () => {
      tenant.value = uni.getStorageSync("tenantId");
      try {
        const result = await tenantList({
          tenantId: uni.getStorageSync("tenantId"),
        });
        if (result?.code == 200) {
          const data = result.data;
          tenant.option = data.map((item) => {
            tenant.currentTenant =
              item.tenantId == tenant.value ? item.tenantName : "";
            return {
              value: item.tenantId,
              label: item.tenantName,
            };
          });
        }
      } catch (error) {
        console.log("租户列表接口报错", error);
      }
    };
    const setData = (data) => {
      const { token, expiresIn, tenantId, tenantName } = data;
      const tokenStore = useTokenStore();
      tokenStore.setCookie("token", token, expiresIn);
      Object.assign(userInfo, data);
      uni.setStorageSync("userInfo", userInfo);
      uni.setStorageSync("tenantId", tenantId);
      tenant.value = tenantId;
      tenant.currentTenant = tenantName;
      isLogin.value = 1;
      if (tenantId) {
        getTenantList();
        getMessageList();
      }
    };
    // 获取消息列表
    const message = reactive({
      list: [],
      total: 0,
    });
    const tagList = {
      0: {
        // 1--合同，2--设计，3--施工，4--其他,为空则查所有
        src: "",
        name: "全部",
        type: "ALL",
        value: 0,
      },
      1: {
        src: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/msg-contract-icon.png",
        name: "合同",
        type: "CONTRACT",
        value: 1,
      },
      2: {
        src: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/msg-design-icon.png",
        name: "设计",
        type: "DESIGN",
        value: 2,
      },
      3: {
        src: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/msg-build-icon.png",
        name: "施工",
        type: "BUILD",
        value: 3,
      },
      4: {
        src: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/msg-other-icon.png",
        name: "其他",
        type: "OTHER",
        value: 4,
      },
    };
    // 通知类型，1--普通消息 2--查看可确认 3--查看可确认拒绝
    const notificationTypeStatusMap = {
      1: { full: "ORDINARY", label: "普通消息" },
      2: { full: "VIEWFORCONFIRMATION", label: "查看可确认" },
      3: { full: "VIEWTOCONFIRMREJECTION", label: "查看可确认拒绝" },
    };
    // 消息状态，1--未查看，2--已查看待确认，3--已确认，4--已同意，5--已拒绝，6--已撤回
    const reverseMessageStatusMap = {
      1: { full: "UNREAD", label: "未查看" },
      2: { full: "VIEWED_PENDING_CONFIRMATION", label: "待确认" },
      3: { full: "CONFIRMED", label: "已确认" },
      4: { full: "AGREED", label: "已同意" },
      5: { full: "REJECTED", label: "已拒绝" },
      6: { full: "WITHDRAWN", label: "已撤回" },
    };
    const getTypeFull = (status) => {
      if (!status) {
        return "";
      }
      return notificationTypeStatusMap[status]?.full || "UNKNOWN_TYPE";
    };
    const getStatusFull = (status) => {
      if (!status) {
        return "";
      }
      return reverseMessageStatusMap[status]?.full || "UNKNOWN_STATUS";
    };
    const getStatusLabel = (status) => {
      if (!status) {
        return "";
      }
      return reverseMessageStatusMap[status]?.label || "未知状态";
    };
    const getMessageList = async () => {
      try {
        const { data } = await messageList({
          msgType: "", //消息类型，1--合同，2--设计，3--施工，4--其他,为空则查所有
          viewType: "",
          size: 3,
          current: 1,
        });
        const records = data?.records || [];
        message.total = data?.total;
        message.list = records.map((item) => {
          const [datePart, timePart] = item.createTime.split(" "); // "2024-11-02 16:11:18"
          const [year, month, day] = datePart.split("-");
          const newItem = {
            ...item,
            year,
            day: month + "-" + day,
            date: datePart,
          };
          return newItem;
        });
      } catch (error) {
        console.log("消息列表接口数据", error);
      }
    };
    // // 获取已读消息数量
    const messageCount = reactive({});
    const getMessageQuantity = async (type) => {
      const msgType = type == 0 ? "" : type;
      try {
        const { data } = await messageQuantity({ msgType });
        Object.assign(messageCount, data);
      } catch (error) {
        console.log(error);
      }
    };
    return {
      isLogin,
      userInfo,
      tenant,
      updateToken,
      getTenantList,
      message,
      tagList,
      getTypeFull,
      getStatusFull,
      getStatusLabel,
      messageList,
      getMessageQuantity,
      messageCount,
      getMessageList,
      setData,
      resetUserInfoAndTenant,
    };
  }
);

export default useUserStore;
